import { io } from 'socket.io-client'
import store from '@/store'
import { Message } from 'element-ui'

import service from "@/utils/request";
class SocketIO {
  constructor() {
    if (SocketIO.instance && SocketIO.instance.io?.connected) {
      return SocketIO.instance
    }
    // 初始化单例对象的属性和方法
    this.value = 'I am the singleton instance'
    console.log('SocketIO init')
    this.io = io(service.defaults.baseURL?.replace('/api', ''), {
      path: '/v2/socket.io',
      query: { token: store.getters.token },
      transports: ['websocket', 'polling']
    })
// 在构造函数中添加断开连接的监听
this.io.on('disconnect', (reason) => {
  console.log('Socket被断开了', reason);
  // 这里可以添加重连逻辑或者通知用户连接已断开
});
    this.io.on('connect', res => {
      this.io.emit(
        'registerListener',
        { 'topics': ['nest_state', 'warn_info'] }
      )
    })
    
    this.io.on('message', res => {
      console.log('SocketUtil message', res)
      if (res?.code === 0) {
        console.log('SocketUtil  connected')
      } else if (res?.code === 600) {
        console.log('SocketUtil message 600', res.topics)
      } else {
        // Message({ message: res.msg, type: 'success' })
        console.log('SocketUtil message error', res.msg)
      }
    })
    this.io.on('debug', res => {
      console.log('SocketUtil debug', res)
    })
    SocketIO.instance = this
    return this
  }

  static getInstance() {
    if (!SocketIO.instance) {
      SocketIO.instance = new SocketIO()
    }
    return SocketIO.instance
  }
}

export default SocketIO
